package org.compiere.process;


import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

import javax.swing.JFileChooser;
import javax.swing.JList;

import org.compiere.model.MBPBankAccount;
import org.compiere.model.MBPartner;
import org.compiere.model.Mhrmpayment;
import org.compiere.model.Mhrmpaymentlist;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.erps.MakeSwift;

public class HrmPaymentSwift extends SvrProcess {
	
	Mhrmpayment hrm_payment = null;
			
	@Override
	protected void prepare() {
		hrm_payment = new Mhrmpayment(getCtx(), getRecord_ID(), null);
	}

	@Override
	protected String doIt() throws Exception {
		String result = Msg.translate(Env.getCtx(), "Success");
		MakeSwift swift = new MakeSwift(Env.getCtx(),hrm_payment);
		swift.make();
		return result;
	}
	
	protected String _doIt() throws Exception {
		if(hrm_payment == null)
			return Msg.translate(Env.getCtx(), "HR.Payment.UploadSwift.Error: hrmPayment is null");
		
		FileOutputStream fos = null;
		OutputStreamWriter out = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try{
			final JFileChooser fc = new JFileChooser();
			fc.setApproveButtonText("Выбрать");//выбрать название для кнопки согласия
			fc.setDialogTitle("Выберите каталог для загрузки файла: Swift.txt");// выбрать название
			JList list = new JList();
			fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

			
			if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(list)) {
				String FileName = fc.getSelectedFile().getAbsolutePath() + "/Swift.txt";
//				String FileName = "/home/alm/Documents/work/swift/swift.txt";
				File file = new File(FileName);//fc.getSelectedFile();
				fos = new FileOutputStream(file);
				out = new OutputStreamWriter(fos, "UTF8");//"CP866");
				
				String sql = " select hrm_payment_list_id from adempiere.hrm_payment_list where hrm_payment_ID = " + hrm_payment.get_ID();

				List<Mhrmpaymentlist> lines = new ArrayList<Mhrmpaymentlist>();
				Mhrmpaymentlist line;
				
				pstmt = null;
				rs = null;
				pstmt = DB.prepareStatement(sql, null);
				rs = pstmt.executeQuery();
				Timestamp ts;
				while (rs.next()) {
					line = new Mhrmpaymentlist(getCtx(), rs.getInt(1), null);
					lines.add(line);
				}
				
				class hrm_salarysum_v{
					BigDecimal opv = new BigDecimal(0);
					BigDecimal ipn = new BigDecimal(0);
					BigDecimal salary = new BigDecimal(0);
					int C_BPartner_ID = 0;
					public int getC_BPartner_ID() {
						return C_BPartner_ID;
					}
					public void setC_BPartner_ID(int c_BPartner_ID) {
						C_BPartner_ID = c_BPartner_ID;
					}
					public BigDecimal getOpv() {
						return opv;
					}
					public void setOpv(BigDecimal opv) {
						this.opv = opv;
					}
					public BigDecimal getIpn() {
						return ipn;
					}
					public void setIpn(BigDecimal ipn) {
						this.ipn = ipn;
					}
					public BigDecimal getSalary() {
						return salary;
					}
					public void setSalary(BigDecimal salary) {
						this.salary = salary;
					}
					
				}
				
				List<hrm_salarysum_v> listOfHrmSalary = new ArrayList<hrm_salarysum_v>();
				
				for(Mhrmpaymentlist l: lines){
					sql = " select hrm_payment_list_id, opv, ipn, result from adempiere.hrm_salarysum_v where hrm_payment_list_id = " + l.gethrm_payment_list_ID();
					
					pstmt = null;
					rs = null;
						
					try{
						pstmt = DB.prepareStatement(sql, null);
						rs = pstmt.executeQuery();
						while (rs.next()) {
							hrm_salarysum_v ll = new hrm_salarysum_v();
							ll.setIpn(rs.getBigDecimal(2));
							ll.setOpv(rs.getBigDecimal(3));
							ll.setSalary(rs.getBigDecimal(4));
							ll.setC_BPartner_ID(l.getC_BPartner_ID());
							listOfHrmSalary.add(ll);
						}
					}catch(SQLException e){
						log.log(Level.WARNING, e.getLocalizedMessage());
					}			
				}
				
				
				//static	
				out.write("{1:F01KKOZKX0000000001000001}"); 	out.write("\r\n");
				out.write("{2:I102SGROSS000000U3003}"); out.write("\r\n");
				out.write("{4:"); 						out.write("\r\n");
				out.write(":20:111111211200673"); 		out.write("\r\n");
				out.write("/NAME/АКЦИОНЕРНОЕ ОБЩЕСТВО  "+'"'+"НАЦИОНАЛЬНЫЙ ИНФОКОММУНИКАЦИОННЫЙ ХОЛДИНГ "+'"'+"ЗЕРДЕ"+'"'); out.write("\r\n");				
				out.write("/RNN/620200331655"); 		out.write("\r\n");
				out.write("/CHIEF/КУРГАНБЕКОВА З. Е.");	out.write("\r\n");		//" + (director == null ? "" : director)); 
				out.write("/MAINBK/НУРАХМЕТОВА А. Т.");	out.write("\r\n");		// + (chiefAcc == null ? "" : chiefAcc)); 
				out.write("/IRS/1"); 					out.write("\r\n");
				out.write("/SECO/6"); 					out.write("\r\n");		
				out.write(":52B:KZKOKZKX");				out.write("\r\n");		// + (swift == null ? "" : swift )); 	//old BIK
				out.write(":57B:KZKOKZKX");				out.write("\r\n");		// + (accountNo3 == null ? "" : accountNo3)); out.write("\r\n");	//new BIK
				out.write(":59:KZ769260010810003398");	out.write("\r\n");		// + (accountNo2 == null ? "" : accountNo2)); 	//fix				
				out.write("/NAME/Казкоммерцбанк АО");	out.write("\r\n");		// + (name == null ? "" : name)); 
				out.write("/RNN/600400055239");			out.write("\r\n");		// + (rnn1 == null ? "" : rnn1)); 
				out.write("/IRS/1");					out.write("\r\n");		// + (resident2 == null ? "" : resident2));  
				out.write("/SECO/9");					out.write("\r\n");		// + (sector2 == null ? "" : sector2)); out.write("\r\n");
				out.write(":70:");						out.write("\r\n");
				out.write("/NUM/"+(hrm_payment.getDocumentNo() == null ? "" : hrm_payment.getDocumentNo())); out.write("\r\n");	
				
				String dateacct = hrm_payment.getDateFrom().toString();
				if(dateacct!=null) dateacct = dateacct.substring(2, 4) + dateacct.substring(5, 7) + dateacct.substring(8,10); 
				out.write("/DATE/"+(dateacct == null ? "" : dateacct)); out.write("\r\n");
				
				out.write("/VO/01"); 					out.write("\r\n");	//fix
				out.write("/SEND/07"); 					out.write("\r\n");	//fix
				out.write("/KNP/311");					out.write("\r\n");	// + (routingno == null ? "" : routingno)); out.write("\r\n");	//new BIK//(kpn == null ? "" : kpn)); out.write("\r\n");
//				out.write("/ASSIGN/" + (hrm_payment.getName() == null ? "" : hrm_payment.getName())); out.write("\r\n");
				
				int row = 1;
				for(hrm_salarysum_v l: listOfHrmSalary){
					out.write(":21:" + row); 				out.write("\r\n");
					
					String payment =  l.getSalary().toString();
					if(payment!=null || payment.equals("")){
						BigDecimal bg = new BigDecimal(payment).setScale(2,BigDecimal.ROUND_UP);
						payment = bg.toPlainString().replace(".", ",");
					} else payment = "0";
					
					out.write(":32B:KZT" + (payment == null ? "0" : payment)); out.write("\r\n");
					out.write(":70:");						out.write("\r\n");
					
					MBPartner  mbp = new MBPartner(getCtx(), l.getC_BPartner_ID(), null);
					out.write("/FM/" + (mbp.getFirstName() == null ? "" : mbp.getFirstName()));	out.write("\r\n");					
					out.write("/NM/" + (mbp.getLastName() == null ? "" : mbp.getLastName()));	out.write("\r\n");
					out.write("/FT/" + (mbp.getMiddleName() == null ? "" : mbp.getMiddleName()));	out.write("\r\n");
					//out.write("/RNN/" + (mbp.getFI_TIN() == null ? "" : mbp.getFI_TIN()));	out.write("\r\n"); TODO Sokolov V. Убрал согласно новым положениям
					out.write("/IDN/" + (mbp.getFI_BIN_IIN() == null ? "" : mbp.getFI_BIN_IIN()));	out.write("\r\n");
					
					
					MBPBankAccount[] ll = mbp.getBankAccounts(true);
					if(ll.length > 0){
						out.write("/LA/" + (ll[0].getAccountNo() == null ? "" : ll[0].getAccountNo()));	out.write("\r\n");
					}else{
						out.write("/LA/");	out.write("\r\n");
					}
					
					row++;	
				}

					// calc total amoumt
					String payment =  hrm_payment.gethrm_amountsalary().toString();
					if(payment!=null || payment.equals("")){
						BigDecimal bg = new BigDecimal(payment).setScale(2,BigDecimal.ROUND_UP);
						payment = bg.toPlainString().replace(".", ",");
					} else payment = "0";
					
				out.write(":32A:" + dateacct +  "KZT" + payment);	out.write("\r\n");
				out.write("-}");	out.write("\r\n");
				
				out.flush();
				out.close();
				fos.close();
			}
		}catch(Exception e){
			//System.out.println(e.toString());
			return "HR.Payment.UploadSwift.Error:" + e.toString();
		} finally {
			DB.close(rs,pstmt);
			rs = null;
			pstmt = null;
		}
		
		
		 
		 return Msg.translate(Env.getCtx(), "Success");
	}
	
	protected void getSalaryTotal(){
		
	}

	
}
